/**
 * Created by yangfan on 2016/9/2.
 */
define(['angular'],function(angular){
    angular.module("uiPagination",[]).directive('uiPagination',[function(){
        return {
            restrict: 'EA',
            template: '<div class="page-list">' +
            '<ul class="pagination" ng-show="conf.totalItems > 0">' +
            '<li ng-class="{disabled: conf.currentPage == 1}" ng-click="prevPage()"><span class="h-l">&nbsp;</span></li>' +
            '<li ng-repeat="item in pageList track by $index" ng-class="{active: item == conf.currentPage, separate: item ==dot}" ' +
            'ng-click="changeCurrentPage(item)">' +
            '<span>{{ item }}</span>' +
            '</li>' +
            '<li ng-class="{disabled:conf.currentPage == conf.numberOfPages}" ng-click="nextPage()"><span class="h-r">&nbsp;</span></li>' +
            '</ul>' +
            '<div class="page-total" ng-show="conf.totalItems > 0">' +
//          '每页<select ng-model="conf.itemsPerPage" ng-options="option for option in conf.perPageOptions " ng-change="changeItemsPerPage()"></select>' +
//         '/共<strong>{{ conf.totalItems }}</strong>条 ' +
            '到<input type="text" ng-model="jumpPageNum" />页' +
            '<a class="h-on"  ng-click="jumpToPage()">确定</a>'+
            '</div>' +
            '<div class="no-items" ng-show="conf.totalItems <= 0"></div>' +
            '</div>',
            replace: true,
            scope: {
                conf: '='
            },
            link: function(scope, element, attrs) {
                var conf = scope.conf;
                scope.dot = "...";
                // 默认分页长度
                var defaultPagesLength = 9;

                // 默认分页选项可调整每页显示的条数
                var defaultPerPageOptions = [10, 15, 20, 30, 50];

                // 默认每页的个数
                var defaultPerPage = 15;

                // 获取分页长度
                if(conf.pagesLength) {
                    // 判断一下分页长度
                    conf.pagesLength = parseInt(conf.pagesLength, 10);

                    if(!conf.pagesLength) {
                        conf.pagesLength = defaultPagesLength;
                    }
                    // 分页长度必须为奇数，如果传偶数时，自动处理
                    if(conf.pagesLength % 2 === 0) {
                        conf.pagesLength += 1;
                    }

                } else {
                    conf.pagesLength = defaultPagesLength
                }

                // 分页选项可调整每页显示的条数
                if(!conf.perPageOptions){
                    conf.perPageOptions = defaultPagesLength;
                }

                // pageList数组
                function getPagination() {

                    // conf.currentPage
                    if(scope.conf.currentPage) {
                        scope.conf.currentPage = parseInt(scope.conf.currentPage, 10);
                      //  scope.conf.currentPage =conf.currentPage;
                    }
                    if(!scope.conf.currentPage) {
                        scope.conf.currentPage = 1;
                    }

                    // conf.totalItems
                    if(scope.conf.totalItems) {
                        scope.conf.totalItems = parseInt(scope.conf.totalItems, 10);
                    }

                    // conf.totalItems
                    if(!scope.conf.totalItems) {
                        scope.conf.totalItems = 0;
                        return;
                    }

                    // conf.itemsPerPage
                    if(scope.conf.itemsPerPage) {
                        scope.conf.itemsPerPage = parseInt(scope.conf.itemsPerPage, 10);
                    }
                    if(!scope.conf.itemsPerPage) {
                        scope.conf.itemsPerPage = defaultPerPage;
                    }

                    // numberOfPages
                    scope.conf.numberOfPages = Math.ceil(scope.conf.totalItems/scope.conf.itemsPerPage);

                    // 如果分页总数>0，并且当前页大于分页总数
                    if(scope.conf.numberOfPages > 0 && scope.conf.currentPage > scope.conf.numberOfPages){
                        scope.conf.currentPage = scope.conf.numberOfPages;
                    }

                    // 如果itemsPerPage在不在perPageOptions数组中，就把itemsPerPage加入这个数组中
                    var perPageOptionsLength = scope.conf.perPageOptions.length;

                    // 定义状态
                    var perPageOptionsStatus;
                    for(var i = 0; i < perPageOptionsLength; i++){
                        if(scope.conf.perPageOptions[i] == scope.conf.itemsPerPage){
                            perPageOptionsStatus = true;
                        }
                    }
                    // 如果itemsPerPage在不在perPageOptions数组中，就把itemsPerPage加入这个数组中
                    if(!perPageOptionsStatus){
                        scope.conf.perPageOptions.push(scope.conf.itemsPerPage);
                    }

                    // 对选项进行sort
                    scope.conf.perPageOptions.sort(function(a, b) {return a - b});


                    // 页码相关
                    scope.pageList = [];
                    if(scope.conf.numberOfPages <= scope.conf.pagesLength){
                        // 判断总页数如果小于等于分页的长度，若小于则直接显示
                        for(i =1; i <= scope.conf.numberOfPages; i++){
                            scope.pageList.push(i);
                        }
                    }else{
                        // 总页数大于分页长度（此时分为三种情况：1.左边没有...2.右边没有...3.左右都有...）
                        // 计算中心偏移量
                        var offset = (scope.conf.pagesLength - 1) / 2;
                        if(scope.conf.currentPage <= offset){
                            // 左边没有...
                            for(i = 1; i <= offset + 1; i++){
                                scope.pageList.push(i);
                            }
                            scope.pageList.push('...');
                            scope.pageList.push(scope.conf.numberOfPages);
                        }else if(scope.conf.currentPage > scope.conf.numberOfPages - offset){
                            scope.pageList.push(1);
                            scope.pageList.push('...');
                            for(i = offset + 1; i >= 1; i--){
                                scope.pageList.push(scope.conf.numberOfPages - i);
                            }
                            scope.pageList.push(scope.conf.numberOfPages);
                        }else{
                            // 最后一种情况，两边都有...
                            scope.pageList.push(1);
                            scope.pageList.push('...');
                            for(i = Math.ceil(offset / 2) ; i >= 1; i--){
                                scope.pageList.push(scope.conf.currentPage - i);
                            }
                            //当前页等于一 则后面不加...
                            if(scope.conf.currentPage!=1){
                                scope.pageList.push(scope.conf.currentPage);
                                for(i = 1; i <= offset / 2; i++){
                                    scope.pageList.push(scope.conf.currentPage + i);
                                }

                                scope.pageList.push('...');
                            }
                            scope.pageList.push(scope.conf.numberOfPages);
                        }
                    }
                    // conf.onChange()函数
                    //if(scope.conf.onChange) {
                    //    scope.conf.onChange();
                    //}
                }

                // prevPage
                scope.prevPage = function() {
                    if(scope.conf.currentPage == 1){
                        return
                    }
                    if(scope.conf.currentPage > 1){
                        scope.conf.currentPage -= 1;
                    }
                   // scope.conf.currentPage = conf.currentPage;
                    //scope.conf.numberOfPages = scope.conf.numberOfPages;
                    getPagination();
                    if(scope.conf.onChange) {
                        scope.conf.onChange();
                    }
                };

                // nextPage
                scope.nextPage = function() {
                    if(scope.conf.currentPage == scope.conf.numberOfPages){
                        return
                    }
                    if(scope.conf.currentPage < scope.conf.numberOfPages){
                        scope.conf.currentPage += 1;
                    }
                       // scope.conf.currentPage = scope.conf.currentPage;
                       // scope.conf.numberOfPages = conf.numberOfPages;
                    getPagination();
                    if(scope.conf.onChange) {
                        scope.conf.onChange();
                    }
                };
                //scope.$watch("conf.numberOfPages",function(){
                //
                //})

                // 变更当前页
                scope.changeCurrentPage = function(item) {

                    if(item == '...'){
                        return;
                    }else{
                        scope.conf.currentPage = item;
                        getPagination();
                       //  conf.onChange()函数
                        if(conf.onChange) {
                            scope.conf.onChange();
                        }
                    }
                };
                //加载页面 执行ajax  获取数据
                scope.changeCurrentPage(1);
                // 修改每页展示的条数
                scope.changeItemsPerPage = function() {

                    // 一发展示条数变更，当前页将重置为1
                    conf.currentPage = 1;

                    getPagination();

                };

                // 跳转页
                scope.jumpToPage = function() {
                    num = scope.jumpPageNum;
                    if(num.match(/\d+/)) {
                        num = parseInt(num, 10);

                        if(num && num != scope.conf.currentPage) {
                            if(num > scope.conf.numberOfPages) {
                                num = scope.conf.numberOfPages;
                            }

                            // 跳转
                            scope.conf.currentPage = num;
                            scope.conf.currentPage = scope.conf.currentPage;
                            getPagination();
                             //conf.onChange()函数
                            if(scope.conf.onChange) {
                                scope.conf.onChange();
                            }
                            scope.jumpPageNum = '';
                        }
                    }
                };

                scope.jumpPageKeyUp = function(e) {
                    var keycode = window.event ? e.keyCode :e.which;

                    if(keycode == 13) {
                        scope.jumpToPage();
                    }
                };

                // scope.$watch('conf.totalItems', function(value, oldValue) {
                //
                //     // 在无值或值相等的时候，去执行onChange事件
                //     if(!value || value == oldValue) {
                //
                //         if(conf.onChange) {
                //             conf.onChange();
                //         }
                //     }
                //     getPagination();
                // })
                scope.$watch("conf.numberOfPages",function(newValue,oldValue){
                    if(newValue!=oldValue ){
                        getPagination();
                    }
                });
                //scope.$watch("conf.itemsPerPage",function(newValue,oldValue){
                //    if(newValue && newValue != oldValue){
                //        scope.changeItemsPerPage();
                //    }
                //});
            }
        };
    }]);
})
